package cn.jwcat.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 跨域配置
 */
@Configuration
public class ReWebMvcConfigurer implements WebMvcConfigurer {
	static final String[] ORIGINS = new String[]{"GET", "POST", "PUT", "DELETE"};
	@Resource
	ReInterceptor reInterceptor;

	@Value("${image.localUrlPath}")
	private String localUrlPath;

	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurer() {
			@Override
			public void addInterceptors(@NotNull InterceptorRegistry registry) {
				registry.addInterceptor(reInterceptor)
					.addPathPatterns("/**")
					.excludePathPatterns("/images/**", "/login", "/logout", "/ip",
						"/favicon.ico", "/app/**", "/error", "/user/register",
						"/file/**", "/user/supplement");
			}

			@Override
			public void addCorsMappings(@NotNull CorsRegistry registry) {
				registry
					.addMapping("/**")
					.allowedOriginPatterns("*")
					.allowedMethods(ORIGINS)
					.allowedHeaders("*")
					.exposedHeaders("*")
					.allowCredentials(true)
					.maxAge(3600L);
			}
		};
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/images/**")
			.addResourceLocations("file:" + localUrlPath + '/');
	}
}
